
import logging
import models

from models import UserInPlaylist, Song
from django.utils import simplejson as json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.api import channel

"""Takes 2 parameters:
- offset
- lang
"""

def get_song_key(lang, songname):
    if lang=='e':
        parent="englishsong"
    else:
        parent="hindisong"
    return db.Key.from_path(parent, songname)

class Nav(webapp.RequestHandler):
    def get(self):
        limit=30
        offset=self.request.get('offset')
        lang=self.request.get('lang')
        q=Song.all()
        q.ancestor(song_key(lang))

        res=q.fetch(limit=limit,offset=offset)
        songslist=[song.songname for song in res]
        jsonobj={'CONTENT':songslist,
                 'COUNT':len(songslist)}
        self.response.out.write(json.dumps(jsonobj))

""" Only needs :
- song
"""
class Search(webapp.RequestHandler):
    def get(self):
        song=self.request.get('song')
        lang=self.request.get('lang')
        q=Song.all()
        q.ancestor(get_song_key(lang))
        q.filter('songname =', song)
        songs=q.fetch(limit=30)
        searches=[song.songname for song in songs]
        jsonobj={'CONTENT':searches,
                 'LENGTH':len(searches)}
        self.response.out.write(json.dumps(jsonobj))
        

def main():
    app=webapp.WSGIApplication([('/pool/nav', Nav),
                                ('/pool/search', Search)], debug=True))
    run_wsgi_app(app)

if __name__=='__main__':
    main()
